from building import *
from SCons.Script import AddOption, GetOption
import os

cwd = GetCurrentDir()
src = []
group = []

def merge_sketch_file_as_cpp(sketch_path, sketch_cpp_filename):
    sketch_cpp_f = open(os.path.join(cwd, sketch_cpp_filename), 'w+')
    sketch_cpp_f.writelines(['#include <RTduino.h>\n', \
                             '#define setup sketch_setup\n', \
                             '#define loop sketch_loop\n', \
                             '#include <{}>\n'.format(sketch_path), \
                             'RTDUINO_SKETCH_LOADER("sketch", sketch_setup, sketch_loop);\n'])
    sketch_cpp_f.close()
    return sketch_cpp_filename

AddOption('--sketch',
        dest = 'sketch',
        type = 'string',
        default = None,
        help = 'set Arduino sketch path and file name')

sketch_path = GetOption('sketch')
if sketch_path == None:
    Return('group')

if os.path.exists(sketch_path) == False or os.path.isfile(sketch_path) == False:
    print('[RTduino] Cannot find the sketch file. Please confirm the ino path and file name is correct!')
    Return('group')

src += [merge_sketch_file_as_cpp(sketch_path, 'sketch.cpp')] # generate a sketch.cpp to include the ino file

group = DefineGroup('RTduino-sketches', src, depend = ['PKG_USING_RTDUINO'])

Return('group')
